from market.models import Asset
from market.models import Player
from market.models import History
from market.models import Strategy
from market.marketData import MarketData
from market.playerData import PlayerData
from market.view import View
from django.utils import simplejson

# helper for createPricesChartJson():
def getPrice( history, theAsset ):
	assetForHisto = history.assetforhistory_set.filter(asset= theAsset)
	if len(assetForHisto) == 1:
		return assetForHisto[0].price
	else:
		return

# return a json with the history of prices per asset
def createPricesChartJson():
	sortedHisto =  [ h for h in History.objects.all()]
	sortedHisto.sort(lambda a,b:cmp(a.time, b.time))
	assetList = [ afh.asset for afh in sortedHisto[len(sortedHisto)-1].assetforhistory_set.all()]

	tmp=    { 'datesList':[{ 'time':str(h.time),
                             'assetsList':[{ 'name':asset.name,
                                             'price':getPrice( h, asset )
                                             } for asset in assetList]
                             } for h in sortedHisto ]
              }
	return simplejson.dumps( tmp )

# helper for getMtM():
def getMtM( history, thePlayer ):
	playerForHisto = history.playerportfolioforhistory_set.filter(player= thePlayer)
	if len(playerForHisto) == 1:
		return playerForHisto[0].portfolioMtM
	else:
		return

# return a json with the history of mtm per player
def createMtMsChartJson():
	sortedHisto =  [ h for h in History.objects.all()]
	sortedHisto.sort(lambda a,b:cmp(a.time, b.time))
	playerList = [ afh.player for afh in sortedHisto[len(sortedHisto)-1].playerportfolioforhistory_set.all()]
	tmp=    { 'datesList':[{ 'time':str(h.time),
                             'playersList':[{ 'name':player.name,
                                              'mtm':getMtM( h, player )
                                             } for player in playerList]
                             } for h in sortedHisto]
              }
	return simplejson.dumps( tmp )

# return a json with the percentage (in mtm of asset) of the player
def getMainViewInMtMJson( player ):

	m = MarketData()
	strat = Strategy.objects.filter( name = player.dbPlayer.mainStrategy )[0]
	n = player.getMainFundTotalNumberOfAssets()
	stratView = View()
	stratView.setViewFromStrategy( strat )
	marketView = m.getMarketView()
	totalValue = m.getStrategyMtM(stratView)
	assetList = [a for a in Asset.objects.all()]
	mtmView = View( assets=assetList, probas=[ player.getNumberOfSpecifiedAssetInMainFund(a)*marketView.getViewOnAsset(a)/totalValue for a in assetList])
	return simplejson.dumps( mtmView.toDictionary() )

# get the sorted list of player ccording to the number of the asset they have
def getRankedPlayers( asset ):
	tmp = [ (PlayerData(p).getNumberOfSpecifiedAssetInAllFunds(asset),p.name) for p in Player.objects.all() ]
    # sort on the number of asset then on the name
	tmp.sort( reverse=True )
	return [ x[1] for x in tmp ]

# return a json with the ranking in case of asset strike
def createRankingTableJson():
	tmp=    { 'assetsList':[{ 'name':a.name,
                             'rankedPlayers':[ {'name':p} for p in getRankedPlayers( a ) ]
                             } for a in Asset.objects.all() ]
              }
	return simplejson.dumps( tmp )

def getJsonPlayerMainViewQty(player):
	playerStrat = Strategy.objects.filter( name = player.dbPlayer.mainStrategy )[0]
	n = player.getMainFundTotalNumberOfAssets()
	# player view
	v = View()
	v.setViewFromStrategy(playerStrat)
	# market value of the strategy
	m = MarketData()
	marketView = m.getMarketView()
	totalValue = m.getStrategyMtM(v)
	tmp = { 'assetsList':[{ 'name':a.name,
                             'playerView':round(v.getViewOnAsset(a),2), 'quantity':round((n * v.getViewOnAsset(a) / 100.0),2),
							 'marketPrice':round(marketView.getViewOnAsset(a) ,2),
							 'value':round((v.getViewOnAsset(a) * n * marketView.getViewOnAsset(a) / 100.0),2)
                             } for a in Asset.objects.all() ]
              }
	return simplejson.dumps( tmp )

